package spar.cancer.data.from.ecxt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import spar.cancer.Cancer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EcxtSocket extends EcxtAbstract {
    private final DatagramSocket s;
    private JSONObject js;
    private final List<String> varsName = new ArrayList<>();

    public EcxtSocket(int port) throws IOException {
        s = new DatagramSocket(port);
    }

    public EcxtSocket(List<Cancer<Double>> objs, int port) throws IOException {
        this(port);
        bind(objs);
    }

    @Override
    public void bind(List<Cancer<Double>> objs) {
        Cancer.setECxtObjs(objs);
        objs.forEach(obj -> {
            varsName.add(obj.getName());
        });
    }

    @Override
    public Map<String, Double> getNextData() {
        Map<String, Double> ret = new HashMap<>();
        for (String var : varsName) {
            ret.put(var, js.getDouble(var));
        }
//        System.out.println(ret);
        return ret;
    }

    @Override
    public boolean hasNextData() {
        iterExit();
        try {
            byte[] data=new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            s.receive(packet);
            js = JSON.parseObject(new String(data, 0 , packet.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean hasNextDataFlag = !js.getBoolean("exit");
        iterEntry(hasNextDataFlag);
        return hasNextDataFlag;
    }

    @Override
    public void close() {
        s.close();
    }
}
